//
//  CocosNodeSlide.m
//  Fifteen puzzle
//
//  Created by vy phan on 7/3/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//
#ifdef USE_CC_SLIDE
#import "CocosNodeSlide.h"
#import "Scene.h"

/*
static inline float clamp(float a, float min, float max) {
	if (a < min) return min;
	if (a > max) return max;
	
	return a;
}
*/

@implementation CocosNodeSlide

- (id)init {
	if (self = [super init]) {
		priority = -1;
		isTouchEnabled = NO;
		inside = NO;
	}
	
	return self;
}


- (int)priority {
	return priority;
}

- (void)setPriority:(int)priority_ {
	if (priority_ == priority) return;
	
	priority = priority_;
	
	if (isTouchEnabled) {
		[[TouchDispatcher sharedDispatcher] setPriority:priority forDelegate:self];
	}
}


- (BOOL)isTouchEnabled {
	return isTouchEnabled;
}

- (void)setIsTouchEnabled:(BOOL)enabled {
	if (enabled == isTouchEnabled) return;
	
	isTouchEnabled = enabled;
	
	if (isTouchEnabled) {
		[[TouchDispatcher sharedDispatcher] addStandardDelegate:self priority:priority];
	} else {
		[[TouchDispatcher sharedDispatcher] removeDelegate:self];
	}
}


- (void)onEnter {
	[super onEnter];
	
	[self setIsTouchEnabled:YES];
}

- (void)onExit {
	[self setIsTouchEnabled:NO];
	
	[super onExit];
}


- (BOOL)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject];
	oldPoint = [touch locationInView:[touch view]];
	
	float x=0, y=0;
	
	CocosNode *ancestor = parent;
	
	while (![ancestor isKindOfClass:[Scene class]]) {
		x += ancestor.position.x - ancestor.anchorPoint.x * ancestor.contentSize.width;
		y += ancestor.position.y - ancestor.anchorPoint.y * ancestor.contentSize.height;
	}
	
	x = oldPoint.y - (x + position_.x + anchorPoint_.x*contentSize_.width);
	y = oldPoint.x - (y + position_.y + anchorPoint_.y*contentSize_.height);
	
	if (x >= 0 && x <= contentSize_.width && y >= 0 && y <= contentSize_.height) {
		printf("\nbegan");
		inside = YES;
		
		return kEventHandled;
	}
	
	return kEventIgnored;
}

- (BOOL)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	if (!inside) return kEventIgnored;
	
	UITouch *touch = [touches anyObject];
	CGPoint point = [touch locationInView:[touch view]];
	
	position_ = CGPointMake(position_.x + point.y - oldPoint.y, position_.y + point.x - oldPoint.x);
	
	oldPoint = point;
	
	return kEventHandled;
}

- (BOOL)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	if (!inside) return kEventIgnored;
	
	inside = NO;
	
	return kEventHandled;
}

@end
#endif